package com.example.myapplication;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import java.util.List;

public class GameCircleActivity extends AppCompatActivity {
    private GameCircleViewModel mViewModel;
    private GameCircleAdapter mAdapter;
    private SwipeRefreshLayout mSwipeRefresh;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game_circle);
        initViews();
        initViewModel();
        loadData();
    }

    private void initViews() {
        mSwipeRefresh = findViewById(R.id.swipe_refresh);
        mSwipeRefresh.setColorSchemeResources(android.R.color.holo_blue_light,
                android.R.color.holo_red_light,
                android.R.color.holo_green_light);

        RecyclerView recyclerView = findViewById(R.id.rv_game_circle);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setHasFixedSize(true);

        mAdapter = new GameCircleAdapter(null,
                this::onGameItemClick,
                this::onGameItemLongClick
        );
        recyclerView.setAdapter(mAdapter);

        mSwipeRefresh.setOnRefreshListener(this::loadData);

        TextView tvBack = findViewById(R.id.tv_back);
        tvBack.setOnClickListener(v -> finish());
    }

    private void initViewModel() {
        mViewModel = new ViewModelProvider(this).get(GameCircleViewModel.class);
        mViewModel.getGameListLiveData().observe(this, gameList -> {
            mSwipeRefresh.setRefreshing(false);
            updateGameList(gameList);
        });
    }

    private void loadData() {
        mSwipeRefresh.setRefreshing(true);
        mViewModel.loadGameData();
    }

    private void updateGameList(List<Game> gameList) {
        if (gameList != null) {
            mAdapter.updateData(gameList);
        } else {
            Toast.makeText(this, "加载数据失败", Toast.LENGTH_SHORT).show();
        }
    }

    private void onGameItemClick(Game game) {
        Intent intent = new Intent(this, GameDetailActivity.class);
        intent.putExtra("GAME_DATA", game);
        startActivity(intent);
    }

    private void onGameItemLongClick(Game game, int position) {
        mViewModel.deleteGame(position);
        Toast.makeText(this, "已删除 " + game.getName(), Toast.LENGTH_SHORT).show();
    }
}
